package com.keson.blue;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Looper;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;

public class StateUtil {
    private static ConnectivityManager mConnectivityManager;
    private static Context context;
    private static WifiManager wifiManager;
    private static float battery;
    private static float vol;
    private static int per;
    private static float volNew;
    private static int volERRcount;
    private static int perNow;
    private static int perERRcount;

    private static TelephonyManager tm;
    private static ConnectivityManager connectivityManager;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    public static int LTEdBm = -1;

    public static void init(Context context) {
        mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        StateUtil.context = context;

        if(tm == null && connectivityManager ==null){
            tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            try{
                listenMobileDbm();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
//    判断是否有网络连接
    @SuppressLint("MissingPermission")
    public static boolean isNetworkConnected() {
        if (context != null) {
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
//    判断WIFI网络是否可用
    @SuppressLint("MissingPermission")
    public static boolean isWifiConnected() {
        if (context != null) {
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isConnected();
            }
        }
        return false;
    }
//    判断MOBILE网络是否可用
    @SuppressLint("MissingPermission")
    public static boolean isMobileConnected() {
        if (context != null) {
            if (Build.MODEL.indexOf("100c")>-1) {
                NetworkCapabilities networkCapabilities = mConnectivityManager.getNetworkCapabilities(mConnectivityManager.getActiveNetwork());
                if (networkCapabilities != null) {
                    return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
                }
            } else {
                NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mMobileNetworkInfo != null) {
                    return mMobileNetworkInfo.isConnected();
                }
            }
        }
        return false;
    }
//    获取当前网络连接的类型信息
//    返回类型为ConnectivityManager.TYPE_MOBILE
    @SuppressLint("MissingPermission")
    public static int getConnectedType() {
        if (context != null) {
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }
    @SuppressLint("MissingPermission")
    public static String getConnectedTypeName() {
        if (context != null) {
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getTypeName();//Ethernet WIFI MOBILE;
            }
        }
        return "未知";
    }

    //wifi信号强度
    public static int getWifiRssi() {
        WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        return mWifiInfo.getRssi();//获取wifi信号强度
//            if (wifi > -50 && wifi < 0) {//最强
//                Log.e(TAG, "最强");
//            } else if (wifi > -70 && wifi < -50) {//较强
//                Log.e(TAG, "较强");
//            } else if (wifi > -80 && wifi < -70) {//较弱
//                Log.e(TAG, "较弱");
//            } else if (wifi > -100 && wifi < -80) {//微弱
//                Log.e(TAG, "微弱");
//            }
    }

    /**
     * 判断以太网网络是否可用
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public static boolean isEtherNetConnected() {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mInternetNetWorkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
            boolean hasInternet = mInternetNetWorkInfo!=null && mInternetNetWorkInfo.isConnected() && mInternetNetWorkInfo.isAvailable();
            return hasInternet;
        }
        return false;
    }



//    wifi操作参考https://blog.csdn.net/weixin_43835637/article/details/91350820
    @SuppressLint("MissingPermission")
    public static void wifiCheckAndReConnect(){
        if(!isNetworkConnected()){
            if(wifiManager.isWifiEnabled()){
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                List<WifiConfiguration> configs =  wifiManager.getConfiguredNetworks();
                if(configs==null){
                    return;
                }
                if(wifiInfo.getSSID().equals("<unknown ssid>")&&configs.size()>0){
                    wifiManager.setWifiEnabled(false);
                    wifiManager.setWifiEnabled(true);
//                    LogUtil.info("WIFI操作","重新开闭wifi开关");
//            for (WifiConfiguration config :configs){
//                if(wifiManager.enableNetwork(config.networkId, true)){
//                    LogUtil.info("WIFI操作","尝试重连："+config.SSID);
//                    break;
//                }else {
//                    LogUtil.info("WIFI操作","尝试重连："+config.SSID+"失败");
//                }
//            }
                }
            }

        }
    }

    //USB设备列表
    public static Collection<UsbDevice> usbDevices(){
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

//        for (UsbDevice device : usbManager.getDeviceList().values()) {
//            System.out.println(device.getDeviceId());
//            System.out.println(device.getProductId());
//            System.out.println(device.getVendorId());
//        }

        return usbManager.getDeviceList().values();
    }


    /**
     * 获取设备拨号运营商
     *原文链接：https://blog.csdn.net/lovelease/article/details/80986771
     * @return ["中国电信CTCC":3]["中国联通CUCC:2]["中国移动CMCC":1]["other":0]["无sim卡":-1]
     */
    public static int getSubscriptionOperatorType() {
        int opeType = -1;
        // No sim
        if (!hasSim()) {
            return opeType;
        }
        String operator = tm.getNetworkOperator();

        if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
            // 中国移动
            opeType = 1;
        }else if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
            // 中国联通
            opeType = 2;
        }else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
            // 中国电信
            opeType = 3;
        } else {
            opeType = 0;
        }
        return opeType;
    }
    public static String getSubscriptionOperatorName() {
        // No sim
        if (!hasSim()) {
            return "无SIM卡";
        }
        String operator = tm.getNetworkOperator();

        if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
            return "中国移动";
        }else if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
            return "中国联通";
        }else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
            return "中国电信";
        } else {
            return "其他";
        }
    }

    /**
     * 获取设备蜂窝网络运营商
     *
     * @return ["中国电信CTCC":3]["中国联通CUCC:2]["中国移动CMCC":1]["other":0]["无sim卡":-1]["数据流量未打开":-2]
     */
    public static int getCellularOperatorType() {
        int opeType = -1;
        // No sim
        if (!hasSim()) {
            return opeType;
        }
        // Mobile data disabled
        if (!isMobileDataEnabled()) {
            opeType = -2;
            return opeType;
        }
        // Check cellular operator
        String operator = tm.getSimOperator();
        // 中国联通
        if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
            opeType = 2;
            // 中国移动
        } else if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
            opeType = 1;
            // 中国电信
        } else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
            opeType = 3;
        } else {
            opeType = 0;
        }
        return opeType;
    }

    /**
     * 判断数据流量开关是否打开
     *
     * @return
     */
    public static boolean isMobileDataEnabled() {
        try {
            Method method = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(connectivityManager);
        } catch (Throwable t) {
            Log.d("isMobileDataEnabled", "Check mobile data encountered exception");
            return false;
        }
    }

    /**
     * 检查手机是否有sim卡
     */
    private static boolean hasSim() {
        String operator = tm.getSimOperator();
        if (TextUtils.isEmpty(operator)) {
            return false;
        }
        return true;
    }

    //获取sim卡iccid
//    https://blog.csdn.net/mingchong2005/article/details/78753920
    @SuppressLint("MissingPermission")
    public static String getIccid() {
        String iccid = tm.getSimSerialNumber();
        if(iccid==null){
            iccid = "";
        }
        return iccid;
    }

    //获取电话号码
    @SuppressLint("MissingPermission")
    public static String getNativePhoneNumber() {
        return tm.getLine1Number();
    }

    //获取IMEI
    @TargetApi(Build.VERSION_CODES.O)
    @SuppressLint("MissingPermission")
    public static String getIMEI(int index) {
        String imei = tm.getImei(index);
        if(TextUtils.isEmpty(imei)){
            //return tm.getMeid(); //如果CDMA制式手机返回MEID
            return "";
        }else {
            return imei;
        }
    }

    @SuppressLint("MissingPermission")
    /**
     * 得到当前的手机蜂窝网络信号强度
     * 获取LTE网络和3G/2G网络的信号强度的方式有一点不同，
     * LTE网络强度是通过解析字符串获取的，
     * 3G/2G网络信号强度是通过API接口函数完成的。
     * asu 与 dbm 之间的换算关系是 dbm=-113 + 2*asu
     */
    public static void listenMobileDbm() throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                PhoneStateListener mylistener =	new PhoneStateListener(){
                    @Override
                    public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                        super.onSignalStrengthsChanged(signalStrength);
                        LTEdBm = -1;
                        String signalInfo = signalStrength.toString();
                        String[] params = signalInfo.split(" ");
                        int Itedbm = Integer.parseInt(params[9]);

                        int asu = signalStrength.getGsmSignalStrength();
                        int dbm = -113 + 2*asu;
                        if(tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE){
//                    System.out.println("LTE:" + Itedbm + "dBm,Detail:" +signalInfo);
                            LTEdBm = Itedbm;
                            tm.listen(null, PhoneStateListener.LISTEN_NONE);
                        }else if(tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA ||
                                tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPA ||
                                tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSUPA ||
                                tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS){
//                    System.out.println("MCDMA:" + dbm + "dBm,Detail:" +signalInfo);
                            LTEdBm = -1;
                        }else{
//                    System.out.println("GSM:" + dbm + "dBm,Detail:" +signalInfo);
                            LTEdBm = -1;
                        }

                    }
                };
                tm.listen(mylistener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
                Looper.loop();
            }
        }).start();

    }

    //有线网卡mac地址
    public static String getEthMac(){
        try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream("/sys/class/net/eth0/address")))) {
            return input.readLine();
        } catch (IOException ex) {
            return "";
        }
    }

    //获取系统参数
    public static String getProperty(String key, String defaultValue) {
        String value = defaultValue;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String)(get.invoke(c, key, defaultValue ));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return value;
        }
    }

    //设置系统参数
    public static void setProperty(String key, String value) {
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method set = c.getMethod("set", String.class, String.class);
            set.invoke(c, key, value );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//        System.out.println("???????????????"+ Build.BRAND);
//        System.out.println("???????????????"+ Build.MODEL);
//        System.out.println("???????????????"+ Build.ID);
//        System.out.println("???????????????"+ Build.DISPLAY);
//        System.out.println("???????????????"+ Build.PRODUCT);
//        System.out.println("???????????????"+ Build.MANUFACTURER);
//        System.out.println("???????????????"+ Build.DEVICE);
//        System.out.println("???????????????"+ Build.HARDWARE);
//        System.out.println("???????????????"+ Build.FINGERPRINT);
//        System.out.println("???????????????"+ Build.SERIAL);
//        System.out.println("???????????????"+ Build.TYPE);
//        System.out.println("???????????????"+ Build.TAGS);
//        System.out.println("???????????????"+ Build.HOST);
//        System.out.println("???????????????"+ Build.USER);
//        System.out.println("???????????????"+ Build.BOOTLOADER);
//        System.out.println("???????????????"+ Build.TIME);
//        System.out.println("???????????????"+ Build.CPU_ABI);
//        System.out.println("???????????????"+ Build.CPU_ABI2);
//        System.out.println("???????????????"+ Build.BOARD);

    //    https://blog.csdn.net/qq_35834055/article/details/72855791

    public static JSONObject getEtherNetInfo(){
        String str = DeviceControlUtil.execRootCmd("ifconfig eth0 |grep Bcast");
        if(str.equals("No such device")){
            return null;
        }else{
            try{
                JSONObject json = JSONObject.parseObject("{" + str.trim().replace("inet addr", "\"ip\"")
                        .replace("Bcast","\"bcast\"")
                        .replace("Mask","\"mask\"")
                        .replaceAll(":",":\"")
                        .replaceAll("  ", "\",") + "\"}");
                json.put("gateway",DeviceControlUtil.execRootCmd("ip route list table 0 | grep \"default via\"").split(" ")[2]);
                json.put("dns1",getProperty("net.dns1",""));
                json.put("dns2",getProperty("net.dns2",""));
                return json;
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
    }

    public static JSONObject getDevStatus(){
        JSONObject object = new JSONObject();
        try{
            object.put("board", Build.MODEL);
            object.put("bluetooth", BluetoothUtil.getBlueToothState());
            object.put("etherMac", getEthMac());
            object.put("firmware", Build.FINGERPRINT);
            object.put("iccid", getIccid());
            object.put("IMEI", "imei1:"+getIMEI(0)+" imei2:"+getIMEI(1)+" sn:"+getProperty("ro.boot.serialno",""));
            object.put("operators", getSubscriptionOperatorName());
            object.put("signalStrength", LTEdBm);
            object.put("signalType", StateUtil.getConnectedTypeName());
            object.put("space", (int)(DeviceControlUtil.getAllStorageSize().getAllStorageAvailablePercent()*100));
            object.put("timeNow", sdf.format(System.currentTimeMillis()));
            object.put("wifiMac", WifiUtil.getMacAddress());
            object.put("wifiAp", WifiUtil.isWifiApEnabled());
            object.put("wifi", WifiUtil.checkState()== WifiManager.WIFI_STATE_ENABLED?true:false);
//            object.put("battery", StateUtil.getBatteryPercent());
//            object.put("dpis", UICheckUtil.getDpi());
//            object.put("tts", TTSUtil.isXunFeiOpen());
//            object.put("vpn", UICheckUtil.isServiceStarted(Constant.context, "de.blinkt.openvpn"));
//            object.put("guard", UICheckUtil.isServiceStarted(Constant.context, "com.keson.guard"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return object;
    }
}
